﻿using UnityEngine;
using System.Collections;

public class CFS_Turret : Photon.MonoBehaviour
{
	[SerializeField] GameObject bulletPrefab = null;
	[SerializeField] Transform gun = null;
	
	[SerializeField] LayerMask gunMask = 0;
	
	[SerializeField] private GameObject[] players;
	[SerializeField] int BulletSpeed = 800;
	
	private GameObject target = null;
	
	bool isShooting = false;
	bool targetInSight = false;

	void Start()
	{
		players = GameObject.FindGameObjectsWithTag("Player");
		
		target = players[0];
		
		if(!photonView.isMine)
			enabled = false;
	}

	void Update()
	{
		photonView.RPC("LookForPlayers",PhotonTargets.All);
		photonView.RPC("Shot", PhotonTargets.All);
	}
	
	[SerializeField] float distToGround = 0.05f;
	int i = 1 << 8;
	bool isGrounded()
	{
		Debug.DrawRay(transform.position, -transform.up * distToGround, Color.red);
		
		return Physics.Raycast(transform.position, -transform.up, distToGround, i);
	}
	
	void FixedUpdate ()
	{
		if(!isGrounded())
		{
			rigidbody.
			rigidbody.velocity += CenterOfGravity.NewGravityDirection(transform.position) * Timing.CustomDeltaTime();
		}
	}
	
	[RPC]
	void Shot()
	{
		if(!isShooting && targetInSight)
		{
			StartCoroutine("Shooting");
		}
		else if(isShooting && !targetInSight)
		{
			StopCoroutine("Shooting");
			isShooting = false;
		}
	}

	[RPC]
	void LookForPlayers()
	{
		for(int i = 0; i < players.Length; i++)
		{
			if(players[i])
			{
	            RaycastHit hit;
				if(Physics.Raycast(gun.position, players[i].transform.position - gun.position, out hit, 100.0f, gunMask))
				{
					if(hit.collider.tag == "Player")
					{
						float distance = Vector3.Distance(gun.position, players[i].transform.position);
						
						if (distance < Vector3.Distance(gun.position, target.transform.position))
						{
							target = players[i];
						}
						
						targetInSight = true;
						
						gun.renderer.material.color = Color.magenta;
					}
					else
					{
						targetInSight = false;
						gun.renderer.material.color = Color.cyan;
					}
				}
			}
			else
			{
				players[i] = null;
			}
		}
	}
	
	IEnumerator Shooting()
	{
		isShooting = true;
		while(target)
		{
			GameObject newBullet = Instantiate(bulletPrefab, gun.position, Quaternion.identity) as GameObject;		
			newBullet.rigidbody.AddForce((target.transform.position - gun.position) *  BulletSpeed);
			
			 yield return new WaitForSeconds(1.0f);
		}
	}
}
